import { defineStore } from 'pinia';

const loadState = () => {
  const savedState = localStorage.getItem('chatStore');
  return savedState ? JSON.parse(savedState) : { userMessages: {} };
};

export const useChatStore = defineStore('chat', {
  state: () => loadState(),
  getters: {
    // 获取所有用户 ID
    getAllUserIds: (state) => {
      return Object.keys(state.userMessages);
    },
  },
  actions: {
    // 添加消息到指定用户的消息列表
    addMessage(userId, message) {
      if (!this.userMessages[userId]) {
        this.userMessages[userId] = [];
      }
      this.userMessages[userId].push(message);
      this.saveState();
    },

    // 获取指定用户的消息列表
    getMessages(userId) {
      return this.userMessages[userId] || [];
    },

    // 保存状态到 localStorage
    saveState() {
      localStorage.setItem('chatStore', JSON.stringify(this.$state));
    },
  },
});